package com.cxs.shopstore.interceptors;

import com.cxs.shopstore.config.JwtPropertiesConfig;
import com.cxs.shopstore.config.RedisTokenConf;
import com.cxs.shopstore.security.token.JwtUtils;
import com.cxs.shopstore.security.token.RsaUtils;
import com.cxs.shopstore.security.token.User;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.MalformedJwtException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/*
 * @Author:cxs
 * @Date:2021/5/19  10:54
 * @Version 1.0
 * 用户身份验证拦截器
 * */
@Slf4j
public class TokenInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;
    @Autowired
    private RedisTokenConf redisTokenConf;
    @Autowired
    private JwtPropertiesConfig jwtPropertiesConfig;
    @Autowired
    private ObjectMapper objectMapper;
    @Override
    public boolean preHandle(
            HttpServletRequest request,
            HttpServletResponse response,
            Object handler) throws Exception {
        Map<String,Object> map = new HashMap<>();
        //获取请求头中的数据信息
        String token = request.getHeader("token");
        String userId = request.getHeader("userId");
        if(token != null && userId != null && userId != "" && token != ""){
            //redis读取数据
            String redisToken = (String) redisTemplate.opsForValue().get(redisTokenConf.getPrefex() + userId);
            //解析token
            User infoFromToken = null;
            try {
                infoFromToken = JwtUtils.getInfoFromToken(redisToken, RsaUtils.getPublicKey(jwtPropertiesConfig.getPubKeyPath()));
            } catch (ExpiredJwtException e) {
                e.printStackTrace();
                map.put("message","token已过期,请重新登陆");
                map.put("status",403);
            } catch (MalformedJwtException e){
                e.printStackTrace();
                map.put("message","token验证失败,请重新登陆");
                map.put("status",403);
            }
            //token校验
            if(token.equals(redisToken) && userId.equals(infoFromToken.getId())){
                log.info("token check success");
                return true;
            }else{
                map.put("status",403);
                map.put("message","身份验证失败,请重新登陆");
                log.error("token check fail");
            }
        }else{
            map.put("status",403);
            map.put("message","权限不足,非法访问");
            log.error("token check fail");
        }
        //前后端分离检验失败发送json到前段
        response.setContentType("text/json;charset=utf-8");
        PrintWriter writer = response.getWriter();
        writer.write(objectMapper.writeValueAsString(map));
        writer.flush();
        writer.close();
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
